package com.kun.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kun.domain.Passenger;
import com.kun.domain.PassengerExample;
import com.kun.mapper.PassengerMapper;
import com.kun.req.PassengerQueryReq;
import com.kun.req.PassengerSaveReq;
import com.kun.resp.PageResp;
import com.kun.resp.PassengerQueryResp;
import com.kun.util.SnowUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @className: PassengerService
 * @Description: ...
 * @author: kunkun
 * @date: 2025/7/9 13:08
 */
@Service
public class PassengerService {
    @Autowired
    private PassengerMapper passengerMapper;

    private Logger LOG = LoggerFactory.getLogger(PassengerService.class);


    public void save(PassengerSaveReq saveReq){
        DateTime date = DateUtil.date();
        Passenger passenger = BeanUtil.copyProperties(saveReq, Passenger.class);
        if(ObjectUtil.isNotNull(saveReq.getId())){  //编辑
            passenger.setUpdateTime(date);
            passengerMapper.updateByPrimaryKeySelective(passenger);
        }  else {       //新增
            passenger.setId(SnowUtil.getSnowflakeNextId());
            passenger.setCreateTime(date);
            passenger.setUpdateTime(date);
            passengerMapper.insert(passenger);
        }
    }

    public PageResp<PassengerQueryResp> queryList(PassengerQueryReq passengerQueryReq){

        PassengerExample passengerExample = new PassengerExample();
        PassengerExample.Criteria criteria = passengerExample.createCriteria();
        if (ObjectUtil.isNotNull(passengerQueryReq.getMemberId())){
            criteria.andMemberIdEqualTo(passengerQueryReq.getMemberId());
        }
        passengerExample.setOrderByClause("id desc");
        PageHelper.startPage(passengerQueryReq.getPage(),passengerQueryReq.getSize());
        List<Passenger> passengers = passengerMapper.selectByExample(passengerExample);
        PageInfo<Passenger> pageInfo = new PageInfo<>(passengers);
        LOG.info("总行数：{}",pageInfo.getTotal());
        LOG.info("总页数：{}",pageInfo.getPages());

        List<PassengerQueryResp> list = BeanUtil.copyToList(passengers, PassengerQueryResp.class);

        PageResp<PassengerQueryResp> resp = new PageResp<>();
        resp.setTotal(pageInfo.getTotal());
        resp.setList(list);

        return resp;
    }


    public void delete(Long id) {
        passengerMapper.deleteByPrimaryKey(id);
    }
}